# -*- coding: utf-8 -*-
'''
@文件    :dependencies.py
@说明    :依赖项
@时间    :2025/02/13 17:14:24
@作者    :浪晋
@版本    :1.0
'''
import jwt as JWT
from fastapi import Security, Depends, HTTPException
from app.core.security import api_key_header
from app.core.plugin import ctx, redis, jwt
from app.settings.config import config


async def validate_api_key(
        api_key: str = Security(api_key_header),
    ):
    """
    @功能    :对要求登录的接口进行token校验
    @参数    :
    @返回值  :
    @时间    :2024/10/19 20:01:04
    @作者    :浪晋
    @版本    :1.0
    """
    if not api_key:
        raise HTTPException(status_code=401, detail="操作未授权")
    if api_key.startswith(config.SECURITY_HEADER_PREFIX):
        token = api_key.replace(config.SECURITY_HEADER_PREFIX + " ", "")
    else:
        raise HTTPException(status_code=401, detail="无效的授权")
    try:
        data = jwt.decrypt_token(token, space=True)
    except JWT.DecodeError:
        raise HTTPException(status_code=401, detail="无效的授权")
    except JWT.ExpiredSignatureError:
        raise HTTPException(status_code=401, detail="授权已过期")
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"{repr(e)}")
    if token != await redis.get(f"{config.REDIS_PREFIX_NAME}:admin:{data.account}"):
        raise HTTPException(status_code=401, detail="授权已过期")
    ctx.set("g", data)
    return data


DeepValidationAdminToken = Security(validate_api_key)  # 检查管理员操作权限